<template>
    <div class='AddKeyValue'>
        <el-drawer :title="'添加('+this.type_n+')-'+this.select_key" v-model="drawerAddVisible" :before-close="before_close" direction="ltr" size="400px">
            <div class="drawer-content">
                <div class="form">
                    <el-scrollbar>
                        <el-form class="affix-container">
                            <!-- 添加方向 -->
                            <el-form-item v-if="type_n == 'list'" label="添加方向" :label-width="70" size="mini" style="margin-bottom: 10px;">
                                <div>
                                    <el-radio v-model="ListaddDirection" :label="1" size="mini">头部</el-radio>
                                    <el-radio v-model="ListaddDirection" :label="2" size="mini">尾部</el-radio>
                                </div>
                            </el-form-item>
                            <!-- 是否覆盖 -->
                            <el-form-item v-else-if="type_n == 'zset' || type_n == 'hash'" label="覆盖添加" :label-width="70" size="mini" style="margin-bottom: 10px;">
                                <div style="height: 100%;display: flex; flex-direction: row;align-items: center;">
                                    <el-switch class="mr-10" v-model="ZsetAddCover" active-color="#ff4949" />
                                    <el-button v-if="type_n == 'zset'" type="text" disabled :style="{color:(ZsetAddCover?'red':'')}">
                                        {{ZsetAddCover ? "当有member相等时，将覆盖更新score" : "当有member相等时，将跳过"}}
                                    </el-button>
                                    <el-button v-else type="text" disabled :style="{color:(ZsetAddCover?'red':'')}">
                                        {{ZsetAddCover ? "当有field相等时，将覆盖更新value" : "当有field相等时，将跳过"}}
                                    </el-button>
                                </div>
                            </el-form-item>
                            <!-- 操作 -->
                            <el-affix v-if="type_n != 'string' && type_n != 'none'" position="top" :offset="60" target=".affix-container">
                                <el-form-item style="margin-bottom: 12px;">
                                    <el-button @click="add_drawer_addOne" type="primary" size="mini">在来一个</el-button>
                                    <el-button @click="add_drawer_deleteKong" type="warning" size="mini">删掉空白</el-button>
                                    <el-button @click="add_drawer_deleteOne" type="danger" size="mini">删掉一个</el-button>
                                    <el-button @click="add_drawer_empty" type="danger" size="mini">清空</el-button>
                                </el-form-item>
                            </el-affix>
                            <div v-if="type_n == 'string'">
                                <el-input v-model="str_value" :rows="10" type="textarea" placeholder="输入内容" />
                            </div>
                            <div v-if="type_n == 'zset'">
                                <el-form-item v-for="item,index in addList" :key="index">
                                    <el-input-number style="width:100%;" size="mini" v-model="addList[index].score" controls-position="right" />
                                    <el-input v-model="addList[index].member" :rows="3" type="textarea" placeholder="输入内容(member)" />
                                </el-form-item>
                            </div>
                            <div v-if="type_n == 'hash'">
                                <el-form-item v-for="item,index in addList" :key="index">
                                    <el-input v-model="addList[index].field" :rows="3" size="mini" placeholder="输入KEY(field)" />
                                    <el-input v-model="addList[index].value" :rows="3" type="textarea" placeholder="输入内容(value)" />
                                </el-form-item>
                            </div>
                            <div v-else-if="type_n == 'set' || type_n == 'list'">
                                <el-form-item v-for="item,index in addList" :key="index">
                                    <el-input v-model="addList[index]" :rows="3" type="textarea" placeholder="输入内容" />
                                </el-form-item>
                            </div>
                        </el-form>
                    </el-scrollbar>
                </div>
                <div class="footer">
                    <el-button @click="drawerAddVisible = false">取 消</el-button>
                    <el-button type="primary" :loading="loading" @click="submit">提交：{{type_n == 'string' ? 1 : addList.length}}</el-button>
                </div>
            </div>
        </el-drawer>
    </div>
</template>

<script>
import { set_sadd } from '@/api/key/set';
import { list_rpush, list_lpush } from '@/api/key/list';
import { zset_zadd } from '@/api/key/zset';
import { hash_hset } from '@/api/key/hash';
import { str_set } from '@/api/key/str';
import { defineComponent, reactive, toRefs } from 'vue';
import { mapGetters } from 'vuex'
import { ElNotification, ElMessageBox, ElMessage } from 'element-plus'
export default defineComponent({
    name: 'AddKeyValue',
    components: {},
    setup(omprops, content) {
        const state = reactive({
            loading: false,
            ListaddDirection: 2, //list的添加反向
            ZsetAddCover: false,
            addList: [],
            str_value: '',

            sj: { //数据结构
                none: '',
                ing: '',
                string: '',
                list: '',
                set: '',
                hash: {
                    field: '',
                    value: ''
                },
                zset: {
                    score: 0,
                    member: ''
                },
            },
            isNall: { // 用来判空
                none: (s) => { return s == '' },
                list: (s) => { return s == '' },
                hash: (s) => { return (s.field == '' || s.value == '') },
                set: (s) => { return s == '' },
                zset: (s) => { return (s.member == '') },
            }
        })

        return toRefs(state)
    },
    props: {
        select_key_new: String,
        modelValue: Boolean,
        type: String
    },
    computed: {
        ...mapGetters([
            'key_type'
        ]),
        type_n() {
            if (typeof this.type == 'undefined') {
                return this.key_type
            }
            return this.type
        },
        select_key() {
            // 如果props有则用
            if (typeof this.select_key_new == 'undefined') {
                return this.$store.getters.select_key
            }
            return this.select_key_new
        },
        drawerAddVisible: {
            set(v) {
                this.$emit('update:modelValue', v)
            },
            get() {
                return this.modelValue
            }
        }
    },
    watch: {
        type_n() {
            this.refresh()
        }
    },
    mounted() {
        this.refresh()
    },
    methods: {
        // 提交
        submit() {
            if (this.type_n == 'string') {
                if (this.str_value == '') {
                    ElMessage("内容为空，无法提交")
                    return
                }
            } else {
                if (this.addList.length <= 0 || (this.addList.length == 1 && this.isNall[this.type_n](this.addList[0]))) {
                    ElMessage("数据为空")
                    return
                }
                for (let i = 0; i < this.addList.length; i++) {
                    if (this.isNall[this.type_n](this.addList[i])) {
                        ElMessage("数据中有空值，无法提交")
                        return
                    }
                }
            }
            this.loading = true
            const sub = {
                string: this.add_str,
                set: this.add_set,
                list: this.add_list,
                zset: this.add_zset,
                hash: this.add_hash,
            }
            sub[this.type_n]().then(() => {
                this.drawerAddVisible = false
                this.refresh()
                this.$emit('refresh', this.select_key)
            }).finally(() => {
                this.loading = false
            })
        },
        add_str() {
            return str_set(this.select_key, this.str_value).then((res) => {
                this.success(`成功->${res.data.map.value}`)
            })
        },
        add_set() {
            return set_sadd(this.select_key, this.addList).then((res) => {
                this.success(`成功添加${res.data.map.success.length}条` +
                    (res.data.map.repeat.length > 0 ? `，其中${res.data.map.repeat.length}条已存在，为:${JSON.stringify(res.data.map.repeat)}` : ''))
            })
        },
        add_list() {
            return (this.ListaddDirection == 2 ? list_rpush : list_lpush)(this.select_key, this.addList).then((res) => {
                this.success(res.data.map.values)
            })
        },
        add_zset() {
            return zset_zadd(this.select_key, this.ZsetAddCover, this.addList).then((res) => {
                const repeat = Object.keys(res.data.map.repeat)
                this.success(`成功添加${Object.keys(res.data.map.success).length}条` +
                    (repeat.length > 0 ? `，其中${repeat.length}条已存在，为:${JSON.stringify(repeat)}` : ''))
            })

        },
        add_hash() {
            return hash_hset(this.select_key, this.ZsetAddCover, this.addList).then((res) => {
                const repeat = Object.keys(res.data.map.repeat)
                this.success(`成功添加${Object.keys(res.data.map.success).length}条` +
                    (repeat.length > 0 ? `，其中${repeat.length}条已存在，为:${JSON.stringify(repeat)}` : ''))
            })
        },


        // 添加成功通知
        success(s) {
            ElNotification({
                title: '添加成功',
                message: s,
                type: 'success',
            })
        },
        // 关闭前回调
        before_close(done) {
            if (this.loading) {
                ElMessage('正在提交内容，请稍后！')
            } else {
                done()
            }
        },
        // 刷新
        refresh() {
            this.str_value = ''
            this.addList = []
            if (this.type_n != 'string' && this.type_n != 'none' && this.type_n != 'ing')
                this.add_drawer_addOne()
        },

        add_drawer_deleteKong() {
            // 删除空白
            this.addList = this.addList.filter((s) => {
                return !this.isNall[this.type_n](s)
            });

            // 为零时,加一个
            if (this.addList.length == 0) {
                this.add_drawer_addOne()
            }
        },
        add_drawer_deleteOne() {
            if (this.addList.length > 1) {
                this.addList.splice(this.addList.length - 1, 1);
            } else {
                ElMessage("再删就没咯")
            }
        },
        add_drawer_addOne() {
            this.addList.push(JSON.parse(JSON.stringify(this.sj[this.type_n])))
        },
        add_drawer_empty() {
            ElMessageBox.confirm('确定要清空吗？', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
            }).then(() => {
                this.refresh()
            })
        },
    },
})
</script>

<style scoped lang="less">
.drawer-content {
    display: flex;
    flex-direction: column;

    height: 100%;
    position: relative;
    overflow-y: hidden;
    .form {
        // padding-right: 10px;
        // margin-right: 10px;
        flex: 1;
        // height: calc(100% - 40px);
        overflow-y: hidden;
        .el-scrollbar {
            padding-right: 10px;
        }
    }
    .footer {
        padding-top: 10px;
        display: flex;
        button {
            flex: 1;
        }
    }
}
</style>
<style lang="less">
.AddKeyValue {
    .el-drawer__header {
        margin-bottom: 0;
        padding-bottom: 20px;
        border-bottom: 1px solid var(--el-border-color-base);
    }
    .el-drawer__body {
        overflow: hidden;
        padding-right: 10px;
        padding-top: 10px;
    }
    .drawer-content {
        .form {
            .affix-container {
                // 数字输入框文字居左
                .el-input-number .el-input__inner {
                    text-align: left;
                }
            }
        }
    }
}
</style>